package blog.rpc;

import com.rabbitmq.client.*;
import constant.Constants;

import java.io.IOException;
import java.util.concurrent.TimeoutException;

public class Service {
    public static void main(String[] args) throws IOException, TimeoutException {
        // 1. 创建连接工厂
        ConnectionFactory factory = new ConnectionFactory();
        // 2. 设置参数
        factory.setHost(Constants.HOST); // ip 的默认值为 localhost
        factory.setPort(Constants.PORT); // 默认值为 5672
        factory.setVirtualHost(Constants.VIRTUAL_HOST); // 虚拟主机，默认值为 /
        // 账号
        factory.setUsername(Constants.USER_NAME); // 用户名，默认为 guest
        factory.setPassword(Constants.USER_PASSWORD); // 密码，默认为 guest
        // 3. 创建连接 Connection
        Connection connection = factory.newConnection(); // 需要处理异常，在此处直接抛出，并不进行处理
        // 4. 创建 Channel
        Channel channel = connection.createChannel();
        // 使用默认的交换机
        // 5. 声明队列
        channel.queueDeclare(Constants.RPC_QUEUE_1, true, false, false, null);
        channel.queueDeclare(Constants.RPC_QUEUE_2, true, false, false, null);
        // 6. 设置同时最多只能获取一条消息
        channel.basicQos(1);
        // 7. 接收消息
        DefaultConsumer consumer = new DefaultConsumer(channel) {
            @Override
            public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
                // 将消息发到队列2中
                AMQP.BasicProperties replayProperties = new AMQP.BasicProperties().
                        builder().
                        correlationId(properties.getCorrelationId()).
                        build();
                // 返回
                String message = new String(body);
                System.out.println("接收到消息: " + message);
                // 响应消息
                String response = "request: " + message + " 接收成功";
                channel.basicPublish("", properties.getReplyTo(), replayProperties, response.getBytes());
                // 对消息进行应答
                channel.basicAck(envelope.getDeliveryTag(), false);
            }
        };
        channel.basicConsume(Constants.RPC_QUEUE_1, false, consumer);
    }
}
